<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/2
 * Time: 21:36
 * 购物车
 */

namespace app\common\model;

use app\common\library\Auth;
use think\Db;
use think\Exception;
use think\Model;
use think\Request;

class Order extends Model
{
	
    // 表名
    protected $name = 'order';
	
	// 自动写入时间戳字段
	protected $autoWriteTimestamp = true;
	
	// 追加属性
	protected $append = [
		'order_status_text',
		'shipping_status_text',
		'pay_status_text',
		'create_time_text',
		'shipping_time_text',
		'confirm_time_text',
		'pay_time_text',
		'order_prom_type_text',
		'is_distribut_text',
		'deleted_text',
		'update_time_text',
		'pay_type_text'
	];
	
	const REIMBURSE_STATUS_N = 0;
	const REIMBURSE_STATUS_W = 1;
	const REIMBURSE_STATUS_Y = 2;
	
	/**
	 * @var array 报销状态
	 */
	public static $reimburseStatusList = [
		self::REIMBURSE_STATUS_N => '未申请',
		self::REIMBURSE_STATUS_W => '审核中',
		self::REIMBURSE_STATUS_Y => '已报销'
	];
	
	const STATUS_CLOSE = 0;
	const STATUS_WAIT_PAYMENT = 1;
	const STATUS_WAIT_DELIVERY = 2;
	const STATUS_WAIT_SIGN = 3;
	const STATUS_SIGN = 4;
	const STATUS_GROUP_WAIT = 5;
	
	/**
	 * 订单状态
	 * @var array
	 */
	public static $_order_status = [
		self::STATUS_WAIT_PAYMENT => '等待买家付款',
		self::STATUS_CLOSE => '交易关闭',
		self::STATUS_WAIT_DELIVERY => '等待卖家发货',
		self::STATUS_WAIT_SIGN => '卖家已发货',
		self::STATUS_SIGN => '交易成功',
		self::STATUS_GROUP_WAIT => '拼团中',
	];


	const CLOSE_TYPE_TIMEOUT = 1;
	const CLOSE_TYPE_USER = 2;
	const CLOSE_TYPE_BUS = 3;
	const CLOSE_TYPE_AFTERSALES = 4;
	
	/**
	 * 订单关闭类型
	 * @var array
	 */
	public static $_close_type = [
		self::CLOSE_TYPE_TIMEOUT => '超时关闭',
		self::CLOSE_TYPE_USER => '买家取消',
		self::CLOSE_TYPE_BUS => '卖家取消',
		self::CLOSE_TYPE_AFTERSALES => '退货关闭'
	];
	
	const PAY_STATUS_N = 0;
	const PAY_STATUS_Y = 1;
	
	/**
	 * 付款状态
	 * @var array
	 */
	public static $_pay_status = [
		self::PAY_STATUS_Y => '已支付',
		self::PAY_STATUS_N => '待付款',
	];
	
	
	const SHIPPING_STATUS_N = 0;
	const SHIPPING_STATUS_W = 1;
	const SHIPPING_STATUS_Y = 2;
	
	/**
	 * 发货状态
	 * @return array
	 */
	public static $_shipping_status = [
		self::SHIPPING_STATUS_N => '待发货',
		self::SHIPPING_STATUS_W => '待签收',
		self::SHIPPING_STATUS_Y => '已签收',
	];
	
	
	
	public function getOrderStatusList()
	{
		return self::$_order_status;
	}
	
	public function getShippingStatusList()
	{
		return self::$_shipping_status;
	}
	
	public function getPayStatusList()
	{
		return self::$_pay_status;
	}
	
	
	const ORDER_TYPE_Group = 4;
	const ORDER_TYPE_NORMAL = 0;
	const ORDER_TYPE_STAGING = 1;
	const ORDER_TYPE_DEPOSIT = 2;
	const ORDER_TYPE_SPIKE = 3;
	
	
	public static $orderTypeList = [
		self::ORDER_TYPE_Group => '拼团订单',
		self::ORDER_TYPE_SPIKE => '秒杀订单',
		self::ORDER_TYPE_DEPOSIT => '押金订单',
		self::ORDER_TYPE_STAGING => '分期订单',
		self::ORDER_TYPE_NORMAL => '普通订单'
	];
	
	
	
	public function getOrderPromTypeList()
	{
		return self::$orderTypeList;
	}
	
	public function getIsDistributList()
	{
		return ['0'=>'未分成', '1' => '已分成'];
	}
	
	const USER_DELETE_N = 0;
	const USER_DELETE_Y = 1;
	public function getDeletedList()
	{
		return [self::USER_DELETE_N => '否', self::USER_DELETE_Y => '是'];
	}
	
	
	public function getOrderStatusTextAttr($value, $data)
	{
		$value = $value ? $value : $data['order_status'];
		$list = $this->getOrderStatusList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	public function getPayTypeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['pay_type'];
		$list = Payment::$_pay_type;
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	public function getShippingStatusTextAttr($value, $data)
	{
		$value = $value ? $value : $data['shipping_status'];
		$list = $this->getShippingStatusList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	public function getPayStatusTextAttr($value, $data)
	{
		$value = $value ? $value : $data['pay_status'];
		$list = $this->getPayStatusList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	public function getCreateTimeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['create_time'];
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	
	public function getShippingTimeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['shipping_time'];
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	
	public function getConfirmTimeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['confirm_time'];
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	
	public function getPayTimeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['pay_time'];
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	
	public function getOrderPromTypeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['order_prom_type'];
		$list = $this->getOrderPromTypeList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	public function getIsDistributTextAttr($value, $data)
	{
		$value = $value ? $value : $data['is_distribut'];
		$list = $this->getIsDistributList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	public function getDeletedTextAttr($value, $data)
	{
		$value = $value ? $value : $data['deleted'];
		$list = $this->getDeletedList();
		return isset($list[$value]) ? $list[$value] : '';
	}
	
	
	public function getUpdateTimeTextAttr($value, $data)
	{
		$value = $value ? $value : $data['update_time'];
		return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
	}
	
	protected function setCreateTimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}
	
	protected function setShippingTimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}
	
	protected function setConfirmTimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}
	
	protected function setPayTimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}
	
	protected function setUpdateTimeAttr($value)
	{
		return $value && !is_numeric($value) ? strtotime($value) : $value;
	}
	
	public function user() {
		return $this->belongsTo('User', 'user_id','id','','left')->setEagerlyType(0);
	}
	
	public function business() {
		return $this->hasOne('Business', 'id', 'business_id','','left')->setEagerlyType(0);
	}
	
	/**
	 * 获取要购买的商品信息
	 * @param $type
	 * @param $cartIds
	 * @param $goodsId
	 * @param $number
	 * @param $priceId
	 * @return array|bool|false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getGoods($type, $cartIds, $goodsId, $number, $priceId){
		$cartModel = new Cart();
		$goods=[];
		if($type == 'cart'){
			if(!$cartIds) {
				$this->error = '请选择要结算的购物车商品';
				return false;
			}
			
			$cartIds = explode(',',$cartIds);
			$goods = Db::name('cart')->alias('c')
				->join('goods g', 'c.goods_id = g.id', 'left')
				->join('goods_spec_price p', 'c.price_id = p.id', 'left')
				->join('business b', 'g.business_id = b.id', 'left')
				->where(['c.id' => ['in', $cartIds],'c.status' => $cartModel::STATUS_Y])
				->field('c.goods_id, c.number, c.price_id,
				g.goods_name, g.shop_price, g.original_image,
				g.store_count as goods_store, g.business_id,
				g.goods_no, g.market_price, g.cost_price, g.commission,
				g.give_integral, p.price as spec_price, p.sku,
				g.is_free_shipping, g.shipping_template_id, g.weight, g.use_point as point, g.give_balance as sendmoney,
				g.goods_type, g.use_day, g.send_number, g.send_day, g.input_ids, g.open_user_grade,
				p.store_count as spec_store, p.sku,
				p.spec_name, b.name as business_name')
				->select();
		} else {
			if(!$goodsId || !$number || $number < 1){
				$this->error = '请选择结算商品和购买数量';
				return false;
			}
			
			if(isset($priceId) && !empty($priceId)){
				$row = Db::name('goods_spec_price')->alias('p')
					->join('goods g', 'p.goods_id = g.id','left')
					->join('business b', 'g.business_id = b.id', 'left')
					->where(['p.id' => $priceId, 'g.id' => $goodsId])
					->field('p.id as price_id, p.goods_id, p.sku,
					g.goods_name, g.shop_price, g.original_image, 
					g.store_count as goods_store, g.business_id,g.commission,
					g.goods_no, g.market_price, g.cost_price, g.give_integral,
					g.is_free_shipping, g.shipping_template_id, g.weight, g.use_point as point, g.give_balance as sendmoney,
					g.goods_type, g.use_day, g.send_number, g.send_day, g.input_ids, g.open_user_grade,
					p.price as spec_price, p.store_count as spec_store, p.sku,
					p.spec_name, b.name as business_name')
					->find();
				if(!$row){
					$this->error = '商品不存在';
					return false;
				}
				
				$row['number'] = $number;
				$goods[] = $row;
			} else {
				$priceItem = Db::name('goods_spec_price')->where(['goods_id' => $goodsId])->find();
				if($priceItem && (!isset($priceId) || empty($priceId))){
					$this->error = '请选择商品规格';
					return false;
				}
				
				$row = Db::name('goods')->alias('g')
					->where(['g.id' => $goodsId])
					->join('business b', 'g.business_id = b.id', 'left')
					->field('g.id as goods_id, g.goods_name, g.shop_price,
					g.original_image, g.store_count as goods_store,
					g.business_id, g.goods_no, g.market_price,g.commission,
					g.is_free_shipping, g.shipping_template_id,
					g.cost_price, g.give_integral,g.weight, g.use_point as point, g.give_balance as sendmoney,
					g.goods_type, g.use_day, g.send_number, g.send_day, g.input_ids, g.open_user_grade,
					b.name as business_name')
					->find();
				if(!$row){
					$this->error = '商品不存在';
					return false;
				}
				
				$row['spec_price'] = $row['spec_store'] = $row['spec_name'] = $row['price_id'] = '';
				
				$row['number'] = $number;
				$goods[] = $row;
			}
		}
		return $goods;
	}
	
	
	/**
	 * 计算并生成订单
	 * @param $userId 用户ID
	 * @param $goods 商品
	 * @param string $type 1计算，其它添加订单
	 * @param array $address 收货地址
	 * @param array $message 订单留言
	 * @return array|bool 添加成功返回订单ID数组
	 * @throws \think\exception\PDOException
	 */
    public function calculationOrder($userId, $goods, $type = 1, $address = [], $message = []) {
    	$busGoods = [];
	    //商品总金额
	    $goodsAmount = 0;
	   
	    //商品总数量
	    $goodsNumber = 0;
    	//运费
    	$freight = 0;
    	
    	//要填写的表单ID
	    $inputIds = [];
	    
	    //订单类型,默认为0，分期购和押金商品不能加入购物车
	    $orderPromType =  0;
	    
	    //押金商品使用天数
	    $useDay = 0;
	    
	    
	    //商品活动类型
	    $activeType = input('post.active_type');
	    
	    //可抵扣积分
	    $allPoint = 0;
	   
    	//按商家区分商品
        foreach($goods as $good) {
	        if($good['goods_type'] == Goods::GOODS_TYPE_2) {
		        $orderPromType = self::ORDER_TYPE_STAGING;
	        } elseif($good['goods_type'] == Goods::GOODS_TYPE_3) {
		        $orderPromType = self::ORDER_TYPE_DEPOSIT;
		        $useDay = isset($good['sku']) ? $good['sku'] : $good['use_day'];
	        }
	        
        	if($activeType == 'group') {
        		//拼团商品
		        $groupGoods = Db::name('goodsGroup')
			        ->where(['goods_id' => $good['goods_id']])
			        ->find();
		        
		        if(!$groupGoods || $groupGoods['status'] != GoodsGroup::STATUS_Y) {
		        	$this->error = '该商品已结束拼团';
		        	return false;
		        }
		        
		        $good['spec_price'] = $groupGoods['price'];
		        $orderPromType = self::ORDER_TYPE_Group;
	        } else if($activeType == 'spike') {
        		$orderPromType = self::ORDER_TYPE_SPIKE;
	        }
        	$bid = $good['business_id'];
        	$price = $good['spec_price']?:$good['shop_price'];
	        $goodsAmount += $price*$good['number'];
	        $goodsNumber += $good['number'];
	        $good['price'] = $price;
	        
	       
	        
	        if($good['input_ids']) {
	        	$inputIds = array_merge($inputIds, explode(',', $good['input_ids']));
	        }
	
	        $allPoint += $good['point'];
	        
	        //商品运费
	        $good['freight'] = 0;
        	if(!isset($busGoods[$bid])){
        	    $busGoods[$bid] = [
        	        'business_id' => $good['business_id'],
		            'business_name' => $good['business_name'],
		            'amount' => $price*$good['number'],
		            'chain_order_no' => '',
		            'order_no' => time().mt_rand(1000,9999),
		            'freight' => 0,
		            'point' => $good['point'],
		            'products' => [
		            	$good
		            ]
	            ];
	        } else {
        		$busGoods[$bid]['amount'] += $price;
		        $busGoods[$bid]['point'] += $good['point'];
		        $busGoods[$bid]['products'][] = $good;
	        }
        }
        
        
        $tempModel = new ShippingTemplate();
        //计算运费
	    foreach($busGoods as $k => $bus){
      
		    //查找用户优惠券
		    $busGoods[$k]['coupons'] = Db::name('userCoupon')
			    ->where([
			    	'user_id' => $userId,
				    'min_amount' => ['elt', $bus['amount']],
				    'start_time' => ['elt', time()],
				    'end_time' => ['egt', time()],
				    'status' => UserCoupon::STATUS_W,
				    'business_id' => $bus['business_id']
			    ])
			    ->field('id, id as couponid, name, min_amount, amount')
			    ->select();
	    }
	    
	    
        if($type == 1){
	        $returnArr = [
		        'orderAmount' => $goodsAmount,
		        'totalNumber' => $goodsNumber,
		        'freight' => $freight,
		        'businessGoods' => array_values($busGoods),
		        'allPoint' => $allPoint,
	        ];
	        return $returnArr;
        }
        
	
	
	    //商家优惠券，格式为：商家1ID=商家1留言&商家2ID=商家2留言。。。
	    $couponStr = input('post.coupons');
	    $coupons = [];
	    if($couponStr){
		    $couponsArr = explode('&',$couponStr);
		    foreach ($couponsArr as $v){
			    $arr = explode('=',$v);
			    $coupons[$arr[0]] = $arr[1];
		    }
	    }
     
	    //查找用户数据
	    $user = Db::name('user')->field('id, integral')->find($userId);
	    $userPoint = $user['integral'];
	    //是否使用积分抵扣
	    $usePoint = input('post.use_point', '0', 'intval');
	    
	    $logModel = new FundsRecord();
	    
        $this->startTrans();
        try {
        	$orderIds = [];
	        foreach($busGoods as $bus){
		        
		        //订单总金额
		        $orderAmount = $bus['amount']+$bus['freight'];
		        $orderData = [
			        'order_no' => $bus['order_no'],
			        'user_id' => $userId,
			        'goods_amount' => $bus['amount'],
			        'freight' => $bus['freight'],
			        'order_amount' => $orderAmount,
			        'total_amount' => $orderAmount,
			        'business_id' => $bus['business_id'],
			        'create_time' => time(),
			        'update_time' => time(),
			        'message' => isset($message[$bus['business_id']])?$message[$bus['business_id']]:'',
			        'chain_order_no' => $bus['chain_order_no'],
			        'order_prom_type' => $orderPromType,
			        'use_day' => $useDay,
			        'integral_money' => 0,
		        ];
		
		        $beforePoint = $userPoint;
		        //如果有使用积分抵扣
		        if($usePoint ==  1 && $userPoint > 0) {
		        	if($userPoint < $bus['point']) {
		        		$integral_money = $userPoint;
			        } else {
		        		$integral_money = $bus['point'];
			        }
			        $userPoint -= $integral_money;
		        	$orderData['order_amount'] -= $integral_money;
		        	$orderData['integral_money'] = $integral_money;
		        	
		        }
		        
		
		        $couponId =isset($coupons[$bus['business_id']]) ? $coupons[$bus['business_id']] : '';
		        if($couponId) {
		        	$coupon = Db::name('userCoupon')
				        ->where([
				        	'user_id' => $userId,
					        'id' => $couponId,
					        'status' => UserCoupon::STATUS_W,
					        'business_id' => $bus['business_id'],
					        'start_time' => ['elt', time()],
					        'end_time' => ['egt', time()]
				        ])
				        ->find();
		        	if(!$coupon) {
		        		throw new Exception($bus['business_name'].' '. $coupon['amount'].'元优惠券不存在');
			        }
			        
			        if($coupon['min_amount'] > $orderData['order_amount']) {
				        throw new Exception($bus['business_name'].' '. $coupon['amount'].'元优惠券不满足使用条件');
			        }
			
			        //记录使用优惠券金额，和使用优惠券后的金额
			        $orderData['coupon_price'] = $coupon['amount'];
			        $orderData['order_amount'] -= $coupon['amount'];
			        
		        }
		
		        
		        $orderData['order_group_id'] = input('post.order_group_id');
		        
		        //如果商品金额小于0，商品为拼团商品更改状态为拼团中，普通商品更改状态为待发货
		        if($orderData['order_amount'] <= 0) {
		        	$orderData['order_amount'] = 0;
		        	if($activeType == 'group') {
		        	    $orderData['order_status'] = Order::STATUS_GROUP_WAIT;
			        } else {
				        $orderData['order_status'] = Order::STATUS_WAIT_SIGN;
			        }
		        }
		        
		        //添加订单
		        $orderId = $this->isUpdate(false)->allowField(true)->insertGetId($orderData);
		        if(!$orderId){
		        	throw new Exception('添加订单出错');
		        }
		        
		        //如果有使用积分，扣除积分，记录资金记录
		        if($orderData['integral_money'] > 0) {
		        	$userRes = Db::name('user')
				        ->where(['id' => $userId])
				        ->setDec('integral', $orderData['integral_money']);
		        	if(!$userRes) {
		        		throw new Exception('扣除积分出错');
			        }
			        
			        $logRes = $logModel->addRecord($userId, $orderData['integral_money'], $beforePoint, $logModel::ACCOUNT_TYPE_INTEGRAL, $logModel::OPE_TYPE_LESS, $logModel::TYPE_PAY_ORDER, $orderId, '订单积分抵扣');
		        	if(!$logRes) {
		        		throw new Exception('记录积分记录出错');
			        }
		        }
		        //如果是秒杀
		        if($orderPromType == self::ORDER_TYPE_SPIKE) {
		            $redis = new \Redis();
		            $redis->connect('127.0.0.1');
		            $redis->auth(config('redis.password'));
		            $userInfo = [
		                'user_id' => $userId,
			            'create_time' => time()
		            ];
					$spikeGoodsId = $bus['products'][0]['goods_id'];
			        $user_queue_key = "spike_goods_".$spikeGoodsId."_user";//当前商品队列的用户情况
			        $redis->hSet($user_queue_key, $userId, serialize($userInfo));
			        $goods_number_key = "spike_goods_number_".$spikeGoodsId;//当前商品的库存队列
			        $redis->lPop($goods_number_key); //减少队列库存
			        
			        //减少数据库库存
			        $spikeGoodsInfoKey = 'spike_goods_'.$spikeGoodsId;
			        $goodsInfo = json_decode($redis->get($spikeGoodsInfoKey), true);
			        $spikeRes = Db::name('goodsSpike')
				        ->where(['id' => $goodsInfo['id']])
				        ->setInc('buy_number');
			        if(!$spikeRes) {
			        	throw new Exception('减少商品库存出错');
			        }
		        }
		        
		        if($couponId) {
			        //更改优惠券状态
			        $couponRes = Db::name('userCoupon')
				        ->where(['id' => $couponId])
				        ->update([
					        'status' => UserCoupon::STATUS_Y,
					        'order_id' => $orderId,
					        'use_time' => time(),
					        'update_time' => time()
				        ]);
			        if(!$couponRes) {
				        throw new Exception('更改优惠券状态出错');
			        }
		        }
		        
		        unset($address['province']);
		        unset($address['city']);
		        unset($address['area']);
		        unset($address['id']);
		        //添加收货地址
		        $addressData = $address;
		        $addressData['order_id'] = $orderId;
		        $addressRes = Db::name('orderAddress')->insert($addressData);
		        
		        if(!$addressRes){
		        	throw new Exception('添加收货地址出错');
		        }
		
		        //添加订单商品
		        
		        foreach($bus['products'] as $goods){
		        	$goods['order_id'] = $orderId;
		        	unset($goods['shop_price']);
		        	unset($goods['goods_store']);
		        	unset($goods['spec_store']);
			        unset($goods['spec_price']);
			        unset($goods['business_name']);
			        unset($goods['is_free_shipping']);
			        unset($goods['shipping_template_id']);
			        unset($goods['weight']);
			        unset($goods['input_ids']);
		        	$goodsRes = Db::name('orderGoods')->insert($goods);
		        	if(!$goodsRes){
		        		throw new Exception('添加购买商品出错');
			        }
			        
			        //减库存
			        if($goods['price_id']){
		        		$descRes = Db::name('goodsSpecPrice')->where(['id' => $goods['price_id']])->dec('store_count');
			        } else {
		        		$descRes = Db::name('goods')->where(['id' => $goods['goods_id']])->dec('store_count');
			        }
			        
			        if(!$descRes){
		        		throw new Exception('减少商品库存出错');
			        }
			        
			        //加销量
			        Db::name('goods')->where(['id' => $goods['goods_id']])->setInc('sale_number', $goods['number']);
		        }
		        
		        
		        $orderIds[] = $orderId;
	        }
	        
	        $this->commit();
	        return $orderIds;
        } catch (Exception $e){
        	$this->error = $e->getMessage();
        	$this->rollback();
        	return false;
        }
        
        
        
    }
	
	/**
	 * 订单列表
	 * @param $where
	 * @param int $page
	 * @return array
	 */
    public function orderList($where, $page=1){
    	$rows = Db::name('order')->alias('o')
		    ->join('business b', 'o.business_id = b.id', 'left')
		    ->join('orderShipping os', 'o.id = os.order_id', 'left')
		    ->join('shipping s', 'os.shipping_id = s.id', 'left')
		    ->where($where)
		    ->field('o.id, o.id as order_id, o.order_status, o.order_no, o.shipping_status, os.shipping_no, os.shipping_id, o.freight, o.order_amount, o.create_time, o.comment_status, o.pay_status, o.close_type,  b.name as business_name, s.name as shipping_name, s.code as shipping_code, o.pay_type, from_unixtime(o.create_time) as create_time, o.coupon_price, o.integral_money, o.reimburse_status')
		    ->order(['o.create_time' => 'desc'])
		    ->page($page,20)
		    ->select();
	    $orders = [];
    	if($rows){
    		$orderIds = [];
    	    foreach($rows as $key => $row){
    	        $orderIds[] = $row['id'];
    	        $row['products'] = [];
    	        $row['order_status_text'] = self::$_order_status[$row['order_status']];
    	        $row['close_type_text'] = $row['close_type']?self::$_close_type[$row['close_type']]:'';
    	        $row['goods_number'] = 0;
    	        $row['pay_name'] = $row['pay_type']>0?Payment::$_pay_type[$row['pay_type']]:'';
		
		        $row['comment_url'] = '';
    	        if($row['order_status'] == self::STATUS_SIGN && $row['comment_status'] == 0) {
    	        	$row['comment_url'] = Request::instance()->domain().url('/mobile/order/comment',['order_id' => $row['id'], 'token' => Auth::instance()->getToken(),'source' => 'app'],'');
	            }
		
		        $row['address'] = Db::name('orderAddress')->alias('ad')
			        ->join('area p','p.id = ad.province_id','left')
			        ->join('area c','c.id = ad.city_id','left')
			        ->join('area a','a.id = ad.area_id','left')
			        ->where(['ad.order_id' => $row['id']])
			        ->field('ad.recipients, ad.mobile, ad.address, p.areaname as province, c.areaname as city, a.areaname as area')
			        ->find();
		        
    	        $orders[$row['id']] = $row;
	        }
	        
	        $goods = Db::name('orderGoods')
		        ->where(['order_id' => ['in', $orderIds]])
		        ->field('id, id as goods_id, order_id,goods_name,price,spec_name,number,original_image, goods_id as gid, point, sendmoney')
		        ->select();
		    if($goods){
			    foreach ($goods as $good){
			    	$good['apply_after_url'] = Request::instance()->domain().url('/mobile/aftersales/selectType',[
			    		'order_id' => $good['order_id'],
						    'item_id' => $good['id'],
						    'token' => Auth::instance()->getToken(),
						    'source' => 'app'
					    ],'');
			    	$orders[$good['order_id']]['goods_number'] += $good['number'];
			        $orders[$good['order_id']]['products'][] = $good;
			    }
		    }
	    }
	    return $orders;
    }
	
	/**
	 * 订单详情
	 * @param $userId 用户ID
	 * @param $id 订单ID
	 * @return array|bool|false|\PDOStatement|string|Model
	 */
	public function orderDetail($userId,$id){
		$row = Db::name('order')->alias('o')
			->join('business b', 'o.business_id = b.id', 'left')
			->join('shipping s', 'o.shipping_id = s.id', 'left')
			->where(['o.user_id' => $userId, 'o.id' => $id])
			->field('o.id, o.id as order_id, o.order_status, o.message, o.goods_amount, o.order_no, o.shipping_status, o.shipping_code as shipping_no, o.shipping_id, o.freight, o.order_amount, o.comment_status, from_unixtime(o.create_time) as create_time, o.pay_time, o.shipping_time, o.confirm_time, o.pay_status, o.close_type, b.name as business_name, s.code as shipping_code, s.name as shipping_name, o.pay_type, o.order_prom_type, o.expire_time, o.coupon_price, o.integral_money, o.reimburse_status')
			->find();
		if(!$row){
			$this->error = '订单不存在';
			return false;
		}
		$row['comment_url'] = '';
		if($row['order_status'] == self::STATUS_SIGN && $row['comment_status'] == 0) {
			$row['comment_url'] = Request::instance()->domain().url('/mobile/order/comment',['order_id' => $row['id'], 'token' => Auth::instance()->getToken(),'source' => 'app'],'');
		}
		
		$row['pay_name'] = $row['pay_type']>0?Payment::$_pay_type[$row['pay_type']]:'';
		
		$row['goods'] = [];
		$goods = Db::name('orderGoods')
			->where(['order_id' => $id])
			->field('id,order_id,goods_name,goods_id,price,spec_name,number,original_image, goods_id as gid, point, sendmoney')
			->select();
		if($goods){
			$row['order_status_text'] = self::$_order_status[$row['order_status']];
			$row['close_type_text'] = $row['close_type']?self::$_close_type[$row['close_type']]:'';
			$row['pay_time'] = $row['pay_time']?date('Y-m-d H:i:s', $row['pay_time']):'';
			$row['shipping_time'] = $row['shipping_time']?date('Y-m-d H:i:s', $row['shipping_time']):'';
			$row['confirm_time'] = $row['confirm_time']?date('Y-m-d H:i:s', $row['confirm_time']):'';
			
			foreach($goods as $key => $good) {
				$goods[$key]['apply_after_url'] = Request::instance()->domain().url('/mobile/aftersales/selectType',[
						'order_id' => $good['order_id'],
						'item_id' => $good['id'],
						'source' => 'app',
						'token' => Auth::instance()->getToken(),
					],'');
			}
			
			$row['goods'] = $goods;
		}
		
		
		$row['address'] = Db::name('orderAddress')->alias('ad')
			->join('area p','p.id = ad.province_id','left')
			->join('area c','c.id = ad.city_id','left')
			->join('area a','a.id = ad.area_id','left')
			->where(['ad.order_id' => $id])
			->field('ad.recipients, ad.mobile, ad.address, p.areaname as province, c.areaname as city, a.areaname as area')
			->find();
		
		$row['order_prom_type_text'] = isset(self::$orderTypeList[$row['order_prom_type']]) ? self::$orderTypeList[$row['order_prom_type']] : '';
		
		$row['delivery_task'] = [
			'need_number' => 1,
			'delivery_number' => 1,
		];
		//如果是分期商品，查找已发货数量
		if($row['order_prom_type'] == self::ORDER_TYPE_STAGING) {
			$row['delivery_task'] = Db::name('deliveryTask')
				->where(['order_id' => $id])
				->field('need_number, delivery_number')
				->find();
		}
		
		$row['expire_date_time'] = date('Y/m/d H:i:s', $row['expire_time']);
		return $row;
	}

	
	/**
	 * 签收订单
	 * @param $id 订单ID
	 * @param $userId 用户ID
	 * @return bool
	 * @throws Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function sign($id, $userId){
		$order = Db::name('order')->find($id);
		
		$updateData = [
			'order_status' => self::STATUS_SIGN,
			'confirm_time' => time(),
			'shipping_status' => self::SHIPPING_STATUS_Y,
			'update_time' => time(),
		];
		
		//如果是押金订单，开始计算使用时间
		if($order['order_prom_type'] == Order::ORDER_TYPE_DEPOSIT) {
			$updateData['expire_time'] = strtotime('+'.$order['use_day'].' days');
		}
		
		$res = Db::name('order')->where(['id' => $id])->update($updateData);
		if(!$res){
			$this->error = '签收出错，请稍候重试';
			return false;
		}
		
		//赠送积分
		$totalIntegral = Db::name('orderGoods')->alias('og')
			->join('goods g', 'og.goods_id = g.id', 'left')
			->where(['og.order_id' => $id])
			->field('og.id, sum(og.give_integral) as total_integral, sum(og.sendmoney) as total_money, sum(g.add_days) as days')
			->find();
		
		$logModel = new FundsRecord();
		$user = Db::name('user')->find($userId);
		if(isset($totalIntegral['total']) && $totalIntegral['total'] > 0) {
			$userRes = Db::name('user')->where(['id' => $userId])->setInc('integral', $totalIntegral['total']);
			if(!$userRes) {
				$this->error = '赠送积分出错';
				return false;
			}
			
			
			$logRes = $logModel->addRecord($userId, $totalIntegral['total'], $user['integral'], $logModel::ACCOUNT_TYPE_INTEGRAL, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_ORDER_GIVE, $id, '购买商品赠送');
			if(!$logRes) {
				$this->error  = '添加积分记录出错';
				return false;
			}
		}
		
		//如果是VIP,赠送金额
		if($user['level'] > 0 && isset($totalIntegral['total_money']) && $totalIntegral['total_money'] > 0) {
			$userRes = Db::name('user')->where(['id' => $userId])->setInc('balance', $totalIntegral['total_money']);
			if(!$userRes) {
				$this->error = '赠送金额出错';
				return false;
			}
			
			
			$logRes = $logModel->addRecord($userId, $totalIntegral['total_money'], $user['balance'], $logModel::ACCOUNT_TYPE_BALANCE, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_ORDER_GIVE, $id, '购买商品赠送');
			if(!$logRes) {
				$this->error  = '添加余额记录出错';
				return false;
			}
		}
		
		//添加话费有效期
		if(isset($totalIntegral['days']) && $totalIntegral['days'] > 0) {
			if($user['phone_time'] < time()) {
				$time = strtotime('+'.$totalIntegral['days'].' days');
			} else {
				$time = strtotime('+'.$totalIntegral['days'].' days', $user['phone_time']);
			}
			
			$timeRes = Db::name('user')->where(['id' => $userId])->setField('phone_time', $time);
			if(!$timeRes) {
				$this->error = '添加话费有效费出错';
				return false;
			}
		}
		
		return true;
	}
	
	/**
	 * 统计订单各状态数量
	 * @param $countWhere
	 * @return array
	 */
	public function countList($countWhere){
		$countWhere = [];
		$count = Db::name('order')
			->where($countWhere)
			->group('order_status')
			->column('count(id) as number', 'order_status');
		
		$status = $this->getOrderStatusList();
		$countList = [];
		$class = [
			self::STATUS_WAIT_PAYMENT => 'btn-danger',
			self::STATUS_CLOSE => 'btn-primary',
			self::STATUS_WAIT_DELIVERY => 'btn-success',
			self::STATUS_WAIT_SIGN => 'btn-info',
			self::STATUS_SIGN => 'btn-warning',
			self::STATUS_GROUP_WAIT => 'btn-success',
		];
		foreach($status as $k => $v){
			$countList[] = [
				'name' => $v,
				'number' => isset($count[$k]) ? $count[$k] : 0,
				'value' => $k,
				'class' => $class[$k]
			];
		}
		
		return $countList;
	}
	
	
	
	/**
	 * 添加返利记录
	 * @param $orderId
	 * @param $userId
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function addRebateRecord($orderId, $userId){
		
		//1、会员商品：购买开通会员权限的商品，返利需要购买用户的三个推荐人和归属代理商
		//   给用户开通会员资格
		//   如果推荐人是代理商，但是等级不是运营商，添加业绩
		
		//2、 代理商品：购买开通代理商、分销商、运营商的商品
		//   只给直接推荐人为代理商的返利，根据不同代理等级返利
		//   如果上级推荐人和上上级推荐人是代理商，但是等级不是普通代理商，添加业绩
		//   购买的用户的上级推荐人中的运营商业绩统计
		//   返利需要数据：判断推荐人的代理商等级，团队业绩(运营商才统计),晋级业绩表(推荐人为普通代理商或高级代理商才统计),奖车业绩表(推荐人两级内，且为高级代理商或运营商才统计)
		
		//3、普通商品，推荐人，归属代理，地区代理返利
		
		//需查找数据：购买用户信息，购买用户推荐人代理商信息，购买用户推荐人的推荐人的代理商信息，购买用户推荐人中的所有代理商
		
		
		//1.查找商品及返利设置
		//2.根据不同商品类型计算不同商品类型的总返利金额
		//3.查找用户信息
		//4.如果购买用户有绑定代理商,查找用户的普通代理商，高级代理商，运营商
		//5.获取推荐人中的是代理商的用户，用于计算业绩
		//6.推荐人的代理商等级
		//7.上上级代理商等级，会员商品的车奖使用
		
		//查找商品及返利设置
		
		//单商品设置的返利金额和返利规则
		$orderGoods = Db::name('orderGoods')->alias('og')
			->join('goods g', 'og.goods_id = g.id', 'left')
			->join('goodsOneRebate r', 'g.id = r.goods_id', 'left')
			->where(['og.order_id' => $orderId])
			->field('og.id as item_id, og.price, g.rebate_type, g.goods_type, g.open_user_grade, g.commission, r.*')
			->select();
		if(!$orderGoods) {
			return true;
		}
		//查找购买用户信息
		$user = Db::name('user')->field('id, parent_path, agent_user_id')->find($userId);
		
		//全局配置
		$rule = Db::name('goodsRebate')->find();
		
		//获取推荐人中的是代理商的用户，用户计算业绩
		$parentAgent = $this->getParentAgent($user['parent_path']);
		
		//上级推荐人
		$parent = [];
		if($user['parent_path']){
			$parents = array_reverse(explode(',', $user['parent_path']));
			$parent = [
				'pid' => isset($parents[0]) ? $parents[0] : '', //上级
				'ppid' => isset($parents[1]) ? $parents[1] : '', //上上级
				'pppid' => isset($parents[2]) ? $parents[2] : '', //上上上级
			];
		}
		
		$agentModel = new Agent();
		
		//推荐人的代理商等级
		if(isset($parent['pid']) && $parent['pid']) {
			$recommendAgent = Db::name('agent')
				->where(['user_id' => $parent['pid'], 'status' => $agentModel::STATUS_Y])
				->find();
		} else {
			$recommendAgent = '';
		}
		
		//上上级代理商等级，会员商品的车奖使用
		if(isset($parent['ppid']) && $parent['ppid']) {
			$ppidAgent = Db::name('agent')
				->where(['user_id' => $parent['ppid'], 'status' => $agentModel::STATUS_Y])
				->find();
		} else {
			$ppidAgent = '';
		}
		
		//查找用户代理
		$agents = [];
		
		//如果用户有归属代理商
		if($user['agent_user_id']){
			$agents = $this->getAgent($user);
			
		}
		
		
		//查找区域代理
		
		$orderAddress = Db::name('orderAddress')->where(['order_id' => $orderId])->find();
		$agentAreaModel = new AgentArea();
		
		$where = '(grade = '.$agentAreaModel::GRADE_PROVINCE.' and province_id = '.$orderAddress['province_id'].') or (grade = '.$agentAreaModel::GRADE_CITY.' and city_id = '.$orderAddress['city_id'].') or (grade = '.$agentAreaModel::GRADE_AREA.' and area_id = '.$orderAddress['area_id'].')';
		
		//查找用户收货地址归属代理
		$areaAgents = Db::name('agentArea')
			->where($where)
			->column('user_id', 'grade');
		
		$areaAgent = [
			'province' => isset($areaAgents[1]) ? $areaAgents[1]: '',
			'city' => isset($areaAgents[2]) ? $areaAgents[3]: '',
			'area' => isset($areaAgents[2]) ? $areaAgents[3]: '',
		];
		
		
		$userModel = new \app\admin\model\User();
		
		foreach($orderGoods as $goods) {
			$goodsType = 0;
			
			if ($goods['open_user_grade'] == $userModel::LEVEL_1) {
				//初级VIP商品
				$goodsType = 1;
//			}elseif($goods['open_user_grade'] == $userModel::LEVEL_2) {
//				//高级VIP商品
//				$goodsType = 2;
			} elseif (in_array($goods['open_user_grade'],
				[$userModel::LEVEL_2, $userModel::LEVEL_3, $userModel::LEVEL_4])) {
				//购买开通代理商身份的为代理商品
				$goodsType = 3;
			}
			
			//获得商品的返利金额和规则
			$rebateAmount = $this->getGoodsRebateAmount($goods, $rule);
			if (!$rebateAmount) {
				continue;
			}
			//记录商品的返利规则
			$ruleRes = Db::name('orderGoods')
				->where(['id' => $rebateAmount['item_id']])
				->update(['rebate_rule' => $rebateAmount['rule']]);
			if (!$ruleRes) {
				$this->error = '保存商品返利规则出错';
				return false;
			}
			
			//普通商品
			$normalGoodsRes = $this->normalGoodsRebate($parent, $agents, $areaAgent, $rebateAmount, $orderId, $userId);
			if (!$normalGoodsRes) {
				$this->error = '订单ID【' . $orderId . '】商品【' . $goods['item_id'] . '】返利出错:' . $this->error;
				return false;
			}
			
			
		}
		return true;
	}
	
	
	/**
	 * 查找归属代理商
	 * @param $user
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	protected function getAgent($user) {
		//查找归属的代理商
		$agent = Db::name('agent')->where(['user_id' => $user['agent_user_id']])->find();
		$agentModel = new Agent();
		switch ($agent['level']) {
			case $agentModel::LEVEL_2:
				//代理商
				$agents = [
					'aid' => $agent['user_id'],
					'aaid' => $agent['pid'],
					'aaaid' => $agent['ppid']
				];
				break;
			case $agentModel::LEVEL_3:
				//分销商，用户的分销商和代理商都他
				$agents = [
					'aid' => $agent['user_id'],
					'aaid' => $agent['user_id'],
					'aaaid' => $agent['pid']
				];
				break;
			case $agentModel::LEVEL_4:
				//营运商，领取分销商+代理商+营运商的钱
				$agents = [
					'aid' => $agent['user_id'],
					'aaid' => $agent['user_id'],
					'aaaid' => $agent['user_id']
				];
				break;
			default:
				$agents = [];
		}
		
		return $agents;
	}
	
	/**
	 * 添加金额和流水
	 * @param $user 返利用户数据
	 * @param $amount 金额
	 * @param string $orderId 佣金订单ID
	 * @param string $remark 备注
	 * @param $relationId 相关用户
	 * @param $rule 返利规则
	 * @param $orderGoodsId 订单商品ID
	 * @return bool
	 * @throws Exception
	 */
	protected function addAmountAndLog($user, $amount, $orderId, $remark, $relationId, $rule, $orderGoodsId){
		
		//添加用户金额
		$userRes = Db::name('user')
			->where(['id' => $user['id']])
			->setInc('balance', $amount);
		if(!$userRes){
			$this->error = '添加订单【'.$orderId.'】用户【'.$user['id'].'】返利金额出错';
			return false;
		}
		
		
		//添加流水记录
		$logModel = new FundsRecord();
		$logRes = $logModel->addRecord($user['id'], $amount, $user['balance'], $logModel::ACCOUNT_TYPE_BALANCE, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_REBATE, $orderId, $remark, $relationId);
		if(!$logRes){
			$this->error = '添加订单【'.$orderId.'】用户【'.$user['id'].'】返利金额流水出错';
			return false;
		}
		
		//添加返利记录
		$recordModel = new RebateRecord();
		
		$recordData = [
			'user_id' => $user['id'],
			'order_id' => $orderId,
			'order_goods_id' => $orderGoodsId,
			'grade' => $user['level'],
			'amount' => $amount,
			'status' => $recordModel::STATUS_Y,
			'rebate_time' => time(),
			'rebate_rule' => $rule,
			'remark' => $remark,
			'agent_grade' => $user['agent_grade'],
			'agent_area_grade' => $user['agent_area_grade']
		];
		
		$recordRes = $recordModel->isUpdate(false)->save($recordData);
		if(!$recordRes){
			$this->error = '添加订单【'.$orderId.'】用户【'.$user['id'].'】返利记录出错';
			return false;
		}
		
		
		return true;
	}
	
	/**
	 * 把订单的返利记录添加到用户余额(中宏的，弃用)
	 * @param $orderId 订单ID
	 * @param $userId 订单的用户ID
	 * @return bool
	 * @throws Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function rebate($orderId, $userId){
		$rows = Db::name('rebateRecord')->where(['order_id' => $orderId])->select();
		$model = new RebateRecord();
		$fundModel = new FundsRecord();
		if($rows) {
			foreach ($rows as $row) {
				//更改状态
				$res = Db::name('rebateRecord')->where(['id' => $row['id']])->update([
					'status' => $model::STATUS_Y,
					'rebate_time' => time(),
					'update_time' => time()
				], ['id' => $row['id']]);
				if(!$res) {
					$this->error = '更改返利状态出错';
					return false;
				}
				
				$user = Db::name('user')->find($row['user_id']);
				//添加金额
				$userRes = Db::name('user')->where(['id' => $row['user_id']])->setInc('balance', $row['amount']);
				if(!$userRes) {
					$this->error = '添加返利金额出错';
					return false;
				}
				
				//添加流水
				$logRes = $fundModel->addRecord($row['user_id'], $row['amount'], $user['balance'], $fundModel::ACCOUNT_TYPE_BALANCE, $fundModel::OPE_TYPE_PLUS, $fundModel::TYPE_REBATE, $row['order_id'], '订单返利', $userId);
				if(!$logRes) {
					$this->error = '添加返利流水记录出错';
					return false;
				}
			}
		}
		
		return true;
	}
	
	/**
	 * 获取推荐人中为代理商的数组
	 * @param $path
	 * @return bool|false|\PDOStatement|string|\think\Collection
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getParentAgent($path){
		if(!$path){
			return false;
		}
		
		$ids = explode(',', $path);
		$ids = array_filter($ids);
		//判断是否禁用
		$agent = Db::name('agent')->alias('a')
			->join('user u', 'u.id = a.user_id', 'left')
			->where(['u.id' => ['in', $ids],'a.status' => Agent::STATUS_Y])
			->order('u.id desc')
			->column('u.id, a.level','u.id');
		if(!$agent){
			return false;
		}
		
		
		$ids = array_reverse($ids);
		$agents = [];
		foreach($ids as $k => $v){
			if(isset($agent[$v])){
				$agents[] = $agent[$v] ;
			}
		}
		
		return $agents;
	}
	
	/**
	 * 会员商品返利 3个推荐人和3个归属代理有返利
	 * 如果推荐人是代理商，但是等级不是运营商，添加业绩
	 * @param $user 用户数据
	 * @param $parent 上级推荐人
	 * @param $rebateAmount 返利金额数据
	 * @param $agents 归属代理商数据
	 * @param $orderId 订单ID
	 * @param $recommendAgent 推荐人代理商信息
	 * @return bool
	 */
	protected function userGoodsRebate($user, $parent, $rebateAmount, $agents, $orderId, $recommendAgent){
		
		try{
			
			//如果存在3级推荐人且3级推荐人的返利金额大于0
			if(isset($parent['pppid']) && $parent['pppid'] && $rebateAmount['pppid'] > 0){
				//判断是否禁用
				$pppuser = $this->getUserAgentGrade($parent['pppid']);
				if($pppuser){
					$pppRes = $this->addAmountAndLog($pppuser, $rebateAmount['pppid'], $orderId, '3级推荐人初级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
					if(!$pppRes) {
						throw new Exception('3级推荐人初级VIP商品添加记录出错');
					}
				}
			}
			
			//如果存在2级推荐人且2级推荐人的返利金额大于0
			if(isset($parent['ppid']) && $parent['ppid'] && $rebateAmount['ppid'] > 0){
				//判断是否禁用
				$ppuser = $this->getUserAgentGrade($parent['ppid']);
				if($ppuser){
					$ppRes = $this->addAmountAndLog($ppuser, $rebateAmount['ppid'], $orderId, '2级推荐人初级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
					if(!$ppRes) {
						throw new Exception('2级推荐人初级VIP商品添加记录出错');
					}
				}
			}
			
			
			//如果存在1级推荐人且1级推荐人的返利金额大于0
			if(isset($parent['pid']) && $parent['pid'] && $rebateAmount['pid'] > 0){
				//判断是否禁用
				$puser = $this->getUserAgentGrade($parent['pid']);
				if($puser){
					$pRes = $this->addAmountAndLog($puser, $rebateAmount['pid'], $orderId, '1级推荐人初级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
					if(!$pRes) {
						throw new Exception('1级推荐人初级VIP商品添加记录出错');
					}
				}
			}
			
			
			//如果有代理商
			if($agents) {
				//如果有归属代理商且所属代理商等级是运营商，那么代理商的所有返利都给他
				if($agents['aid'] && $agents['aid'] == $agents['aaid'] && $agents['aid'] == $agents['aaaid']){
					$agentMoney = $rebateAmount['aid']+$rebateAmount['aaid']+$rebateAmount['aaaid'];
					if($agentMoney > 0){
						$aUser = $this->getUserAgentGrade($agents['aid']);
						$aRes = $this->addAmountAndLog($aUser, $agentMoney, $orderId, '运营商初级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aRes) {
							throw new Exception('运营商初级VIP商品添加记录出错');
						}
					}
				}elseif ($agents['aid'] && $agents['aid'] == $agents['aaid']){
					//如果所属代理商等级为高级代理商，那么他获得普通代理商和高级代理商的返利
					
					//高级代理商的金额
					$agentMoney = $rebateAmount['aid']+$rebateAmount['aaid'];
					//如果存在高级代理商且返利金额大于0
					if($agentMoney > 0){
						$aUser = $this->getUserAgentGrade($agents['aid']);
						$aRes = $this->addAmountAndLog($aUser, $agentMoney, $orderId, '分销商初级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aRes) {
							throw new Exception('分销商初级VIP商品添加记录出错');
						}
					}
					
					//如果存在运营商且返利金额大于0
					if($rebateAmount['aaaid'] > 0 && $agents['aaaid']){
						$aaaUser = $this->getUserAgentGrade($agents['aaaid']);
						$aaaRes = $this->addAmountAndLog($aaaUser, $agentMoney, $orderId, '运营商初级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aaaRes) {
							throw new Exception('运营商初级VIP商品添加记录出错');
						}
					}
				} else {
					//如果存在普通代理商且返利金额大于0
					if($rebateAmount['aid'] > 0 && $agents['aid']){
						$aUser = $this->getUserAgentGrade($agents['aid']);
						$aRes = $this->addAmountAndLog($aUser, $rebateAmount['aid'], $orderId, '代理商初级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aRes) {
							throw new Exception('代理商初级VIP商品添加记录出错');
						}
					}
					
					//如果存在运营商且返利金额大于0
					if($rebateAmount['aaid'] > 0 && $agents['aaid']){
						$aaUser = $this->getUserAgentGrade($agents['aaid']);
						$aaRes = $this->addAmountAndLog($aaUser, $rebateAmount['aaid'], $orderId, '分销商初级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aaRes) {
							throw new Exception('分销商初级VIP商品添加记录出错');
						}
					}
					
					//如果存在运营商且返利金额大于0
					if($rebateAmount['aaaid'] > 0 && $agents['aaaid']){
						$aaaUser = $this->getUserAgentGrade($agents['aaaid']);
						$aaaRes = $this->addAmountAndLog($aaaUser, $rebateAmount['aaaid'], $orderId, '代理商初级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aaaRes) {
							throw new Exception('运营商初级VIP商品添加记录出错');
						}
					}
				}
			}
			
			
			return true;
		} catch(Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	
	
	/**
	 * 会员商品返利 3个推荐人和3个归属代理有返利
	 * 如果推荐人是代理商，但是等级不是运营商，添加业绩
	 * @param $user 用户数据
	 * @param $parent 上级推荐人
	 * @param $rebateAmount 返利金额数据
	 * @param $agents 归属代理商数据
	 * @param $orderId 订单ID
	 * @param $recommendAgent 推荐人代理商信息
	 * @return bool
	 */
	protected function VipGoodsRebate($user, $parent, $rebateAmount, $agents, $orderId, $recommendAgent){
		
		try{
			
			//如果存在2级推荐人
			if($parent['ppid']){
				//判断是否禁用
				$ppuser = $this->getUserAgentGrade($parent['ppid']);
				if($ppuser && $ppuser['level'] > 0){
					$amount = $ppuser['level'] == \app\admin\model\User::LEVEL_1 ? 20 : 100;
					$ppRes = $this->addAmountAndLog($ppuser, $amount, $orderId, '2级推荐人高级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
					if(!$ppRes) {
						throw new Exception('2级推荐人高级VIP商品添加记录出错');
					}
				}
			}
			
			
			//如果存在1级推荐人且1级推荐人的返利金额大于0
			if($parent['pid'] && $rebateAmount['pid'] > 0){
				//判断是否禁用
				$puser = $this->getUserAgentGrade($parent['pid']);
				if($puser && $puser['level'] > 0){
					$amount = $puser['level'] == \app\admin\model\User::LEVEL_1 ? 30 : 320;
					$pRes = $this->addAmountAndLog($puser, $amount, $orderId, '1级推荐人高级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
					if(!$pRes) {
						throw new Exception('1级推荐人高级VIP商品添加记录出错');
					}
				}
			}
			
			
			//如果有代理商
			if($agents) {
				//如果有归属代理商且所属代理商等级是运营商，那么代理商的所有返利都给他
				if($agents['aid'] && $agents['aid'] == $agents['aaid'] && $agents['aid'] == $agents['aaaid']){
					$agentMoney = $rebateAmount['aid']+$rebateAmount['aaid']+$rebateAmount['aaaid'];
					if($agentMoney > 0){
						$aUser = $this->getUserAgentGrade($agents['aid']);
						$aRes = $this->addAmountAndLog($aUser, $agentMoney, $orderId, '运营商高级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aRes) {
							throw new Exception('运营商高级VIP商品添加记录出错');
						}
					}
				}elseif ($agents['aid'] && $agents['aid'] == $agents['aaid']){
					//如果所属代理商等级为高级代理商，那么他获得普通代理商和高级代理商的返利
					
					//高级代理商的金额
					$agentMoney = $rebateAmount['aid']+$rebateAmount['aaid'];
					//如果存在高级代理商且返利金额大于0
					if($agentMoney > 0){
						$aUser = $this->getUserAgentGrade($agents['aid']);
						$aRes = $this->addAmountAndLog($aUser, $agentMoney, $orderId, '分销商高级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aRes) {
							throw new Exception('分销商高级VIP商品添加记录出错');
						}
					}
					
					//如果存在运营商且返利金额大于0
					if($rebateAmount['aaaid'] > 0 && $agents['aaaid']){
						$aaaUser = $this->getUserAgentGrade($agents['aaaid']);
						$aaaRes = $this->addAmountAndLog($aaaUser, $agentMoney, $orderId, '运营商高级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aaaRes) {
							throw new Exception('运营商高级VIP商品添加记录出错');
						}
					}
				} else {
					//如果存在普通代理商且返利金额大于0
					if($rebateAmount['aid'] > 0 && $agents['aid']){
						$aUser = $this->getUserAgentGrade($agents['aid']);
						$aRes = $this->addAmountAndLog($aUser, $rebateAmount['aid'], $orderId, '代理商高级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aRes) {
							throw new Exception('代理商高级VIP商品添加记录出错');
						}
					}
					
					//如果存在运营商且返利金额大于0
					if($rebateAmount['aaid'] > 0 && $agents['aaid']){
						$aaUser = $this->getUserAgentGrade($agents['aaid']);
						$aaRes = $this->addAmountAndLog($aaUser, $rebateAmount['aaid'], $orderId, '分销商高级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aaRes) {
							throw new Exception('分销商高级VIP商品添加记录出错');
						}
					}
					
					//如果存在运营商且返利金额大于0
					if($rebateAmount['aaaid'] > 0 && $agents['aaaid']){
						$aaaUser = $this->getUserAgentGrade($agents['aaaid']);
						$aaaRes = $this->addAmountAndLog($aaaUser, $rebateAmount['aaaid'], $orderId, '代理商高级VIP商品返利', $user['id'], $rebateAmount['rule'], $rebateAmount['item_id']);
						if(!$aaaRes) {
							throw new Exception('运营商高级VIP商品添加记录出错');
						}
					}
				}
			}
			
			
			return true;
		} catch(Exception $e) {
			$this->error = $e->getMessage();
			return false;
		}
	}
	
	
	/**
	 * 普通商品返利
	 * @param $parent 上3级推荐人
	 * @param $agents 上3级归属代理
	 * @param $areaAgent 地区代理
	 * @param $rebateAmount 返利金额数据
	 * @param $orderId 订单ID
	 * @param $userId 用户ID
	 * @return bool
	 * @throws Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	protected function normalGoodsRebate($parent, $agents, $areaAgent, $rebateAmount,$orderId, $userId){
		
		//一级推荐人
		if(isset($parent['pid']) && $parent['pid'] && $rebateAmount['pid'] > 0){
			$pUser = $this->getUserAgentGrade($parent['pid']);
			$pidRes = $this->addAmountAndLog($pUser, $rebateAmount['pid'], $orderId, '普通商品一级推荐人返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
			if(!$pidRes) {
				$this->error = '订单ID【'.$orderId.'】一级推荐人'.$this->error;
				return false;
			}
		}
		
		//二级推荐人
		if(isset($parent['ppid']) && $parent['ppid'] && $rebateAmount['ppid'] > 0){
			$ppUser = $this->getUserAgentGrade($parent['ppid']);
			$ppidRes = $this->addAmountAndLog($ppUser, $rebateAmount['ppid'], $orderId, '普通商品二级推荐人返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
			if(!$ppidRes) {
				$this->error = '订单ID【'.$orderId.'】二级推荐人'.$this->error;
				return false;
			}
		}
		
		//三级推荐人
		if(isset($parent['pppid']) && $parent['pppid'] && $rebateAmount['pppid'] > 0){
			$pppUser = $this->getUserAgentGrade($parent['pppid']);
			$pppidRes = $this->addAmountAndLog($pppUser, $rebateAmount['pppid'], $orderId, '普通商品三级推荐人返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
			if(!$pppidRes) {
				$this->error = '订单ID【'.$orderId.'】三级推荐人'.$this->error;
				return false;
			}
		}
		
		//如果有代理商，且代理商返利费用大于0
		if($agents && ($rebateAmount['aid'] > 0 || $rebateAmount['aaid'] > 0 || $rebateAmount['aaaid'] > 0)) {
			if($agents['aid'] == $agents['aaid'] && $agents['aid'] == $agents['aaaid']){
				//所属代理是高级代理商
				$amount = $rebateAmount['aid'] + $rebateAmount['aaid'] + $rebateAmount['aaaid'];
				$aUser = $this->getUserAgentGrade($parent['aid']);
				$aRes = $this->addAmountAndLog($aUser, $amount, $orderId, '普通商品直接代理为运营商返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
				if(!$aRes) {
					$this->error = '订单ID【'.$orderId.'】直接代理为运营商返利'.$this->error;
					return false;
				}
			} elseif ($agents['aid'] == $agents['aaid']){
				$aaAmount = $rebateAmount['aid'] + $rebateAmount['aaid'];
				if($aaAmount > 0){
					$aUser = $this->getUserAgentGrade($agents['aid']);
					$aRes = $this->addAmountAndLog($aUser, $aaAmount, $orderId, '直接代理为分销商返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
					if(!$aRes) {
						$this->error = '订单ID【'.$orderId.'】直接代理为分销商返利'.$this->error;
						return false;
					}
				}
				
				if(!$agents['aaaid'] && $rebateAmount['aaaid'] > 0){
					$aaaUser = $this->getUserAgentGrade($agents['aaaid']);
					$aaaRes = $this->addAmountAndLog($aaaUser, $rebateAmount['aaaid'], $orderId, '普通商品运营商返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
					if(!$aaaRes) {
						$this->error = '订单ID【'.$orderId.'】运营商返利'.$this->error;
						return false;
					}
				}
			} else {
				if($agents['aid'] && $rebateAmount['aid'] > 0){
					$aUser = $this->getUserAgentGrade($agents['aid']);
					$aRes = $this->addAmountAndLog($aUser, $rebateAmount['aid'], $orderId, '普通商品代理商返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
					if(!$aRes) {
						$this->error = '订单ID【'.$orderId.'】代理商返利'.$this->error;
						return false;
					}
				}
				
				if($agents['aaid'] && $rebateAmount['aaid'] > 0){
					$aaUser = $this->getUserAgentGrade($agents['aaid']);
					$aaRes = $this->addAmountAndLog($aaUser, $rebateAmount['aaid'], $orderId, '普通商品分销商返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
					if(!$aaRes) {
						$this->error = '订单ID【'.$orderId.'】分销商返利'.$this->error;
						return false;
					}
				}
				
				if(!$agents['aaaid'] && $rebateAmount['aaaid'] > 0){
					$aaaUser = $this->getUserAgentGrade($agents['aaaid']);
					$aaaRes = $this->addAmountAndLog($aaaUser, $rebateAmount['aaaid'], $orderId, '运营商返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
					if(!$aaaRes) {
						$this->error = '订单ID【'.$orderId.'】运营商返利'.$this->error;
						return false;
					}
				}
			}
		}
		
		
		//区域代理返利
		if($areaAgent['province'] && $rebateAmount['province'] > 0) {
			$provinceUser = $this->getUserAgentGrade($areaAgent['province']);
			$provinceRes = $this->addAmountAndLog($provinceUser, $rebateAmount['province'], $orderId, '普通商品省级代理返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
			if(!$provinceRes) {
				$this->error = '订单ID【'.$orderId.'】省级代理返利出错'.$this->error;
				return false;
			}
		}
		
		if($areaAgent['city'] && $rebateAmount['city'] > 0) {
			$cityUser = $this->getUserAgentGrade($areaAgent['city']);
			$cityRes = $this->addAmountAndLog($cityUser, $rebateAmount['city'], $orderId, '普通商品市级代理返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
			if(!$cityRes) {
				$this->error = '订单ID【'.$orderId.'】市级代理返利出错'.$this->error;
				return false;
			}
		}
		
		if($areaAgent['area'] && $rebateAmount['area'] > 0) {
			$areaUser = $this->getUserAgentGrade($areaAgent['area']);
			$areaRes = $this->addAmountAndLog($areaUser, $rebateAmount['area'], $orderId, '普通商品区级代理返利', $userId, $rebateAmount['rule'], $rebateAmount['item_id']);
			if(!$areaRes) {
				$this->error = '订单ID【'.$orderId.'】区级代理返利出错'.$this->error;
				return false;
			}
		}
		
		return true;
	}
	
	
	/**
	 * 计算商品的返利金额和返利规则
	 * @param $goods
	 * @param $rule
	 * @return array
	 */
	protected function getGoodsRebateAmount($goods, $rule){
		
		$rebateAmount = [];
		
		if($goods['rebate_type'] == Goods::REBATE_GLOBAL && $rule) {
			$goodsRule = '全局配置，佣金【'.$goods['commission'].'】，上级【'.$rule['pid'].'】，上上级【'.$rule['ppid'].'】， 上上上级【'.$rule['pppid'].'】，代理商【'.$rule['aid'].'】，分销商【'.$rule['aaid'].'】，运营商【'.$rule['aaaid'].'】，省代【'.$rule['province'].'】，市代【'.$rule['city'].'】，区代【'.$rule['area'].'】';
			
			//全局配置返利
			$rebateAmount['pid'] = round($goods['commission'] * $rule['pid'],2);
			$rebateAmount['ppid'] = round($goods['commission'] * $rule['ppid'],2);
			$rebateAmount['pppid'] = round($goods['commission'] * $rule['pppid'],2);
			$rebateAmount['aid'] = round($goods['commission'] * $rule['aid'],2);
			$rebateAmount['aaid'] = round($goods['commission'] * $rule['aaid'],2);
			$rebateAmount['aaaid'] = round($goods['commission'] * $rule['aaaid'],2);
			$rebateAmount['province'] = round($goods['commission'] * $rule['province'],2);
			$rebateAmount['city'] = round($goods['commission'] * $rule['city'],2);
			$rebateAmount['area'] = round($goods['commission'] * $rule['area'],2);
			$rebateAmount['rule'] = $goodsRule;
			$rebateAmount['item_id'] = $goods['item_id'];
			$rebateAmount['price'] = $goods['price'];
		} else {
			//单独配置返利
			if($goods['id']) {
				$goodsRule = '单独配,上级【'.$goods['pid'].'】，上上级【'.$goods['ppid'].'】， 上上上级【'.$goods['pppid'].'】，代理商【'.$goods['aid'].'】，分销商【'.$goods['aaid'].'】，运营商【'.$goods['aaaid'].'】，省代【'.$goods['province'].'】，市代【'.$goods['city'].'】，区代【'.$goods['area'].'】';
				$rebateAmount['pid'] = $goods['pid'];
				$rebateAmount['ppid'] = $goods['ppid'];
				$rebateAmount['pppid'] = $goods['pppid'];
				$rebateAmount['aid'] = $goods['aid'];
				$rebateAmount['aaid'] = $goods['aaid'];
				$rebateAmount['aaaid'] = $goods['aaaid'];
				$rebateAmount['province'] = $goods['province'];
				$rebateAmount['city'] = $goods['city'];
				$rebateAmount['area'] = $goods['area'];
				$rebateAmount['rule'] = $goodsRule;
				$rebateAmount['item_id'] = $goods['item_id'];
				$rebateAmount['price'] = $goods['price'];
			}
		}
		
		return $rebateAmount;
	}
	
	/**
	 * 获取用户的基本信息及代理等级，区域代理等级
	 * @param $userid
	 * @return array|false|\PDOStatement|string|Model
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	protected function getUserAgentGrade($userid){
		$row = Db::name('user')->alias('u')
			->join('agent a', 'a.user_id = u.id', 'left')
			->join('agentArea aa', 'aa.user_id = u.id', 'left')
			->where(['u.id' => $userid, 'u.status' => \app\admin\model\User::STATUS_Y])
			->field('u.*, a.level as agent_grade, aa.grade as agent_area_grade')
			->find();
		return $row;
	}
	
	
	/**
	 * 开通对应商品的会员资格和代理资料
	 * @param $orderId
	 * @param $userId
	 * @return bool
	 * @throws Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function openUserGrade($orderId, $userId) {
		$gradeGoods = Db::name('orderGoods')
			->where(['order_id' => $orderId])
			->order(['open_user_grade' => 'DESC'])
			->field('id, open_user_grade')
			->find();
		
		$userModel = new \app\admin\model\User();
		if(!$gradeGoods || $gradeGoods['open_user_grade'] == $userModel::LEVEL_0) {
			return true;
		}
		
		$grade = $gradeGoods['open_user_grade'];
		$user = Db::name('user')->find($userId);
		
		if(!$user || $user['level'] >= $grade) {
			return true;
		}
		
		
		//更改用户等级
		$res = Db::name('user')
			->where(['id' => $userId])
			->update(['level' => $grade]);
		if(!$res) {
			$this->error  = '更改会员等级出错';
			return false;
		}
		
		//添加等级变更记录
		$logModel = new UserLevelRecord();
		$logRes = $logModel->addRecord($user['id'], $user['level'], $grade, '', '购买商品变更等级');
		if(!$logRes) {
			$this->error = '添加会员等级更改记录出错';
			return false;
		}
		
		
		if($grade > $userModel::LEVEL_1) {
			//代理商品,判断是否已经是代理商
			$agentTable = Db::name('agent');
			$agentRow = $agentTable->where(['user_id' => $userId])->find();
			if($agentRow) {
				//已经是代理商了， 表示是升级，更改等级和上级结构
				$data['level'] = $grade;
				$data['ppid'] = '';
				if($grade == Agent::LEVEL_3) {
					//分销商
					$data['pid'] = $agentRow['ppid'];
				} elseif($grade == Agent::LEVEL_4) {
					//运营商
					$data['pid'] = '';
				}
				$res = $agentTable->where(['user_id' => $userId])->update($data);
				if(!$res) {
					$this->error = '更改代理商等级出错';
					return false;
				}
			} else {
				//不是代理商，要查找归属代理商
				$parentAgent = $this->getAgent($user);
				$insertData = [
					'user_id' => $userId,
					'name' => $user['username'],
					'level' => $grade,
					'create_time' => time(),
					'update_time' => time(),
				];
				
				if($parentAgent) {
					if($grade == Agent::LEVEL_2) {
						$insertData['pid'] = $parentAgent['aaid'];
						$insertData['ppid'] = $parentAgent['aaaid'];
					} elseif($grade == Agent::LEVEL_3) {
						$insertData['pid'] = $parentAgent['aaaid'];
					}
				}
				
				$res = $agentTable->insert($insertData);
				if(!$res) {
					$this->error = '开通代理商出错';
					return false;
				}
			}
		}
		
		return true;
	}
	
	
	/**
	 * 订单支付完成后的操作
	 * @param $order 订单信息
	 * @param $payType 支付方式
	 * @param string $trade_no 第三方支付订单号
	 * @return bool
	 * @throws Exception
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function paySuccess($order, $payType, $trade_no = ''){
		$orderModel = new Order();
		$logModel = new FundsRecord();
		
		//拼团订单支付成功，状态为拼团中
		if($order['order_prom_type'] == Order::ORDER_TYPE_Group) {
			$orderStatus =  $orderModel::STATUS_GROUP_WAIT;
		} else {
			$orderStatus = $orderModel::STATUS_WAIT_DELIVERY;
		}
		
		$data = [
			'order_status' => $orderStatus,
			'pay_status' => $orderModel::PAY_STATUS_Y,
			'pay_code' => $trade_no,
			'pay_type' => $payType,
			'pay_time' => time(),
			'transaction_id' => $trade_no,
			'update_time' => time()
		];
		
		$orderRes = Db::name('order')->where(['id' => $order['id']])->update($data);
		if(!$orderRes) {
			$this->error = '更改订单状态出错';
			return false;
		}
		
		//更改拼团订单数量或开团
		if($order['order_prom_type'] == Order::ORDER_TYPE_Group) {
			$groupModel = new OrderGroup();
			$goods = Db::name('orderGoods')->where(['order_id' => $order['id']])->find();
			$groupRes = $groupModel->changeNumber($order, $goods['goods_id']);
			if(!$groupRes) {
				$this->error = $groupModel->getError();
				return false;
			}
		}
		
		//添加返利记录
		$rebateRes = $orderModel->addRebateRecord($order['id'], $order['user_id']);
		if(!$rebateRes) {
			$this->error = $orderModel->getError();
			return false;
		}
		
		//开通VIP或代理商
		$openRes = $orderModel->openUserGrade($order['id'], $order['user_id']);
		if(!$openRes) {
			$this->error = $orderModel->getError();
			return false;
		}
		
		//如果是分期商品订单，添加发货任务
		if($order['order_prom_type'] == Order::ORDER_TYPE_STAGING) {
			$taskModel = new DeliveryTask();
			$taskRes = $taskModel->createTask($order['id']);
			if(!$taskRes) {
				$this->error = '添加分期商品发货任务出错:'.$taskModel->getError();
				return false;
			}
		}
		
		//如果是押金商品，给押金余额加钱
		if($order['order_prom_type'] == Order::ORDER_TYPE_DEPOSIT && $order['order_amount'] > 0) {
			$depositRes = Db::name('user')
				->where(['id' => $order['user_id']])
				->setInc('deposit_balance', $order['order_amount']);
			if(!$depositRes) {
				$this->error = '添加押金金额出错';
				return false;
			}
			
			$user = Db::name('user')->find($order['user_id']);
			
			//记录流水
			$fundsRes = $logModel->addRecord($user['id'], $order['order_amount'],$user['deposit_balance'], $logModel::ACCOUNT_TYPE_DEPOSIT, $logModel::OPE_TYPE_PLUS, $logModel::TYPE_GOODS_DEPOSIT, $order['id'], '商品押金');
			
			if(!$fundsRes) {
				$this->error = '添加押金记录出错';
				return false;
			}
			
		}
		
		
		return true;
	}
}
